package com.jeesite.modules.task.action.service;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.home.entity.ImageDto;
import com.jeesite.modules.msg.entity.content.PcMsgContent;
import com.jeesite.modules.msg.utils.MsgPushUtils;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.action.entity.DcSupTaskAction;
import com.jeesite.modules.task.action.entity.DcSupTaskActionDto;
import com.jeesite.modules.task.action.entity.DcSupTaskInfoAction;
import com.jeesite.modules.task.action.entity.DcSupTaskScheduled;
import com.jeesite.modules.task.arrange.dao.DcSupTaskInfoArrangeDao;
import com.jeesite.modules.task.arrange.entity.DcSupTaskInfoArrange;
import com.jeesite.modules.task.audit.entity.DcSupTaskAudit;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfo;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoService;
import com.jeesite.modules.task.feedback.entity.DcSupTaskFeedback;
import com.jeesite.modules.task.feedback.service.DcSupTaskFeedbackService;
import com.jeesite.modules.task.receive.entity.TaskReceiveDto;
import com.jeesite.modules.utils.OfficeUtil;
import lombok.RequiredArgsConstructor;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.LineSpacingRule;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务部署分发表Service
 *
 * @author zrr
 * @version 2022-03-03
 */
@Service
@Transactional(readOnly=false)
@RequiredArgsConstructor
public class DcSupTaskActionService extends CrudService<DcSupTaskActionDao, DcSupTaskAction> {

    private final DcSupTaskActionDao dcSupTaskActionDao;

    private final DcSupTaskFeedbackService dcSupTaskFeedbackService;

    private final DcSupTaskInfoArrangeDao dcSupTaskInfoArrangeDao;

    private final SysOfficeUnitService sysOfficeUnitService;
    @Autowired
    private DcSupTaskInfoService dcSupTaskInfoService;

    /**
     * 获取单条数据
     *
     * @param dcSupTaskAction
     * @return
     */
    @Override
    public DcSupTaskAction get(DcSupTaskAction dcSupTaskAction) {
        return super.get(dcSupTaskAction);
    }

    /**
     * 查询分页数据
     *
     * @param dcSupTaskAction 查询条件
     * @return
     */
    @Override
    public Page<DcSupTaskAction> findPage(DcSupTaskAction dcSupTaskAction) {
        return super.findPage(dcSupTaskAction);
    }

    /**
     * 查询列表数据
     *
     * @param dcSupTaskAction
     * @return
     */
    @Override
    public List<DcSupTaskAction> findList(DcSupTaskAction dcSupTaskAction) {
        return super.findList(dcSupTaskAction);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param dcSupTaskAction
     */
    @Override
    @Transactional(readOnly = false)
    public void save(DcSupTaskAction dcSupTaskAction) {
        super.save(dcSupTaskAction);
        // 保存上传图片
        FileUploadUtils.saveFileUpload(dcSupTaskAction, dcSupTaskAction.getId(), "dcSupTaskAction_image");
        // 保存上传附件
        FileUploadUtils.saveFileUpload(dcSupTaskAction, dcSupTaskAction.getId(), "dcSupTaskAction_file");
    }

    /**
     * 更新状态
     *
     * @param dcSupTaskAction
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(DcSupTaskAction dcSupTaskAction) {
        super.updateStatus(dcSupTaskAction);
    }

    /**
     * 删除数据
     *
     * @param dcSupTaskAction
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(DcSupTaskAction dcSupTaskAction) {
        super.delete(dcSupTaskAction);
    }


    /**
     * 查询未办列表
     *
     * @param dcSupTaskAction
     * @return
     */
    public Page<DcSupTaskInfoAction> noCompleteListData(DcSupTaskInfoAction dcSupTaskAction) {
        String userCode = UserUtils.getUser().getUserCode();
        String currentOfficeCode = OfficeUtil.getCurrentOffice().getOfficeCode();
        // 过滤管理员
        if (!StringUtils.equals("system", userCode)) {
            dcSupTaskAction.setTransferOrgCode(currentOfficeCode);
            dcSupTaskAction.setTransferUserCode(userCode);
        }
        //获取所有待办信息
        List<DcSupTaskInfoAction> dcSupTaskActions = dcSupTaskActionDao.findNoCompleteListData(dcSupTaskAction);
        //获取待办 actionId
        List<String> actionId = dcSupTaskActions.stream().map(DcSupTaskInfoAction::getId).collect(Collectors.toList());
        //根据actionId 查找任务反馈信息
        List<DcSupTaskFeedback> feedbacks = dcSupTaskFeedbackService.findLastTaskFeedback(actionId);
        //把反馈数据 转成key,value 方式  actionId:DcSupTaskFeedbacks 并循环塞到返回信息中
        Map<String, List<DcSupTaskFeedback>> feedbackMap = feedbacks.stream().collect(Collectors.groupingBy(DcSupTaskFeedback::getActionId));
        dcSupTaskActions.forEach(dcSupTaskInfoAction -> {
            List<DcSupTaskFeedback> back = feedbackMap.get(dcSupTaskInfoAction.getId());
            if (back != null && !back.isEmpty()) {
                dcSupTaskInfoAction.setFeedback(back.get(0));
            } else {
                dcSupTaskInfoAction.setFeedback(new DcSupTaskFeedback());
            }
        });
        //按照时间排序 asc
        List<DcSupTaskInfoAction> sortList = null;
        String orderBy = dcSupTaskAction.getOrderBy();
        String name = Sort.Direction.ASC.name().toLowerCase(Locale.ROOT);
        if (orderBy == null || orderBy.equals("") || orderBy.contains(name)) {
            sortList = dcSupTaskActions.
                    stream().
                    sorted(Comparator.comparing(x -> x.getFeedback().getFeedbackEndTimeStr(), Comparator.nullsLast(Comparator.naturalOrder()))).
                    collect(Collectors.toList());
            //分组
            sortList = dcSupTaskInfoActionDbOrderByStatus(sortList);
        } else {
            sortList = dcSupTaskActions.
                    stream().
                    sorted(Comparator.comparing(x -> x.getFeedback().getFeedbackEndTimeStr(), Comparator.nullsLast(Comparator.reverseOrder()))).
                    collect(Collectors.toList());
            sortList = dcSupTaskInfoActionDbOrderByStatus(sortList);
        }
        return dcSupTaskAction.getPage().setList(sortList);
    }

    public Page<DcSupTaskInfoAction> noCompleteListData2(DcSupTaskInfoAction dcSupTaskAction) {
        if(StringUtils.isBlank(dcSupTaskAction.getOrderBy())||StringUtils.equals("feedbackEndTimeStr asc",dcSupTaskAction.getOrderBy())){
            dcSupTaskAction.setRemarks("1");
        }else if(StringUtils.equals("feedbackEndTimeStr desc",dcSupTaskAction.getOrderBy())){
            dcSupTaskAction.setRemarks("2");
        }
        String userCode = UserUtils.getUser().getUserCode();
        String currentOfficeCode = OfficeUtil.getCurrentOffice().getOfficeCode();
        // 过滤管理员
        if (!StringUtils.equals("system", userCode)) {
            dcSupTaskAction.setTransferOrgCode(currentOfficeCode);
            dcSupTaskAction.setTransferUserCode(userCode);
        }
        //获取所有待办信息
        List<DcSupTaskInfoAction> dcSupTaskActions = dcSupTaskActionDao.findNoCompleteListData(dcSupTaskAction);

        for (int i = 0; i < dcSupTaskActions.size(); i++) {
            if(StringUtils.isNotBlank(dcSupTaskActions.get(i).getFeedbackEndTimeStr())){
                if(DateUtils.parseDate(dcSupTaskActions.get(i).getFeedbackEndTimeStr()).getTime()< System.currentTimeMillis()){
                    dcSupTaskActions.get(i).setColour("red");
                }
            }
            if(dcSupTaskActions.get(i).getDecomposeTaskId()==null){
                dcSupTaskActions.get(i).setDecomposeTaskId("");
            }
        }
        return dcSupTaskAction.getPage().setList(dcSupTaskActions);
    }

    //待办按照任务状态排序
    public List<DcSupTaskInfoAction> dcSupTaskInfoActionDbOrderByStatus(List<DcSupTaskInfoAction> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        Map<String, List<DcSupTaskInfoAction>> groupby = list.stream().collect(Collectors.groupingBy(DcSupTaskInfoAction::getTaskStatus));
        //按照顺序组合 3进行中、4已结束
        List<DcSupTaskInfoAction> sortStatusList = new ArrayList<>();
        if (groupby.containsKey("1")) {
            sortStatusList.addAll(groupby.get("1"));
        }
        if (groupby.containsKey("2")) {
            sortStatusList.addAll(groupby.get("2"));
        }
        if (groupby.containsKey("3")) {
            sortStatusList.addAll(groupby.get("3"));
        }
        if (groupby.containsKey("4")) {
            sortStatusList.addAll(groupby.get("4"));
        }
        return sortStatusList;
    }


    /**
     * 查询已办列表
     *
     * @param dcSupTaskAction
     * @return
     */
    public Page<DcSupTaskInfoAction> completeListData(DcSupTaskInfoAction dcSupTaskAction) {
        String userCode = UserUtils.getUser().getUserCode();
        String currentOfficeCode = OfficeUtil.getCurrentOffice().getOfficeCode();
        // 过滤管理员
        if (!StringUtils.equals("system", userCode)) {
            dcSupTaskAction.setTransferOrgCode(currentOfficeCode);
            dcSupTaskAction.setTransferUserCode(userCode);
        }
        //获取已办信息 条件 info表状态完成 并且待办表是转办数据
        List<DcSupTaskInfoAction> dcSupTaskActions = dcSupTaskActionDao.findCompleteListData(dcSupTaskAction);
        return dcSupTaskAction.getPage().setList(dcSupTaskActions);
    }

    /**
     * 待办批示列表数据
     */
    public Page<DcSupTaskActionDto> findListData(DcSupTaskActionDto dcSupTaskActionDto, HttpServletRequest request, HttpServletResponse response) {
        dcSupTaskActionDto.setPage(new Page<>(request, response));
        //获取当前登录人的领导编码
        String userCode = UserUtils.getUser().getUserCode();
        // 过滤管理员
        if (!StringUtils.equals("system", userCode)) {
            dcSupTaskActionDto.setExplainCode(userCode);
        }
        List<DcSupTaskActionDto> dcSupTaskActionDtoList = dcSupTaskActionDao.findDcSupTaskActionDtoList(dcSupTaskActionDto);
        //任务状态排序
        return dcSupTaskActionDto.getPage().setList(dcSupTaskActionDtoList);
    }


    /**
     * 待办批示保存数据（插入或更新）
     *
     * @param dcSupTaskAction
     */
    @Transactional(readOnly = false)
    public void updateData(DcSupTaskAction dcSupTaskAction) {
        //封装数据
        dcSupTaskAction.setExplainTime(new Date());
        dcSupTaskActionDao.updateData(dcSupTaskAction);
    }

    /**
     * 弃用
     * 用scheduledActionTaskProgress
     */
    public void scheduledActionEveryday() {
        //1.查出action表的list  注:过滤已结束数据
        List<DcSupTaskAction> actionList = dcSupTaskActionDao.findscheduledActionList();

        //2.遍历actionList
        for (DcSupTaskAction action : actionList) {
            DcSupTaskAction updateAction = new DcSupTaskAction();
            updateAction.setId(action.getId());
            updateAction.setRemarks2(DateUtils.getDateTime() + "定时任务");
            //3.查询add表和feedback联合表
            List<DcSupTaskScheduled> feedback = dcSupTaskActionDao.findscheduledFeedbackList(action.getId());
			/*如果最后反馈时间未反馈,则进度滞后,状态码1
			如果最新一条反馈时间大于反馈截止时间,则逾期反馈,状态码2
			默认序时推进,状态码3
			当最后一条已反馈时,则已完成,状态码4*/
            int a = 0;
            int b = 0;
            int c = 0;
            int d = 0;
            int length = feedback.size();
            String status = "bug";
            List<Integer> list = new ArrayList<>();
            for (DcSupTaskScheduled dc : feedback) {
                list.add(Integer.valueOf(dc.getStatus()));
                if ("1".equals(dc.getStatus())) {
                    a++;
                }
                if ("2".equals(dc.getStatus())) {
                    b++;
                }
                if ("3".equals(dc.getStatus())) {
                    if ("1".equals(dc.getStatus1())) {
                        d++;
                    } else {
                        c++;
                    }

                }
                if ("4".equals(dc.getStatus())) {
                    if ("1".equals(dc.getStatus1())) {
                        d++;
                    } else {
                        c++;
                    }
                }
                if (Integer.valueOf(dc.getStatus()) < 3) {
                    status = dc.getStatus();
                }
            }
            //    1进度滞后   2逾期反馈   3序时推进   4已完成
            if (d == length) {//全部已完成
                updateAction.setTaskProgress("4");
            } else if (c == length) {//全部序时推进
                updateAction.setTaskProgress("3");
            } else if (b + d == length) {//有逾期反馈+已完成=需要反馈的反馈总数
                updateAction.setTaskProgress("4");
            } else if (c != length && d != length && a != 0 && b != 0) {//有滞后时序和逾期反馈取最新的
                updateAction.setTaskProgress(status);
            } else if (c != length && d != length && b != 0) {//有逾期反馈
                updateAction.setTaskProgress("2");
            } else if (c != length && d != length && a != 0) {//有进度滞后
                updateAction.setTaskProgress("1");
            } else if (d != length && c + d == length) {//已完成+序时推进,得序时推进
                updateAction.setTaskProgress("3");
            } else {
                updateAction.setTaskProgress(status);
            }
            dcSupTaskActionDao.updateProgress(updateAction);
        }
    }

    /**
     * time<time2返回true,否则返回false
     * 时间比较
     *
     * @param time
     * @param time2
     * @return
     */

    public static Boolean DateCompare(Date time, Date time2) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time2);
        int now_y = calendar.get(Calendar.YEAR);//得到年份
        int now_m = calendar.get(Calendar.MONTH) + 1;//得到月份
        int now_d = calendar.get(Calendar.DATE);//得到月份中今天的号数
        calendar.setTime(time);
        int y = calendar.get(Calendar.YEAR);//得到年份
        int m = calendar.get(Calendar.MONTH) + 1;//得到月份
        int d = calendar.get(Calendar.DATE);//得到月份中今天的号数
        System.out.println("时间是：" + y + "-" + m + "-" + d);
        if (now_y < y || (now_y == y && now_m < m) || (now_y == y && now_m == m && now_d <= d)) {
        } else {
            return true;
        }
        return false;
    }


    /**
     * 获取秘书一科任务查询
     *
     * @param dcSupTaskInfo
     * @return
     */
    public Page<DcSupTaskInfo> actionSecretaryFeedbackList(DcSupTaskInfo dcSupTaskInfo) {
        // 查询数据
        List<DcSupTaskInfo> dcSupTaskInfos = getDcSupTaskInfoActions(dcSupTaskInfo);

        for (DcSupTaskInfo info:dcSupTaskInfos) {
            System.out.println(info.getMessageNumber());
        }
        for (int i = 0; i < dcSupTaskInfos.size(); i++) {
            if ("1".equals(dcSupTaskInfos.get(i).getTaskProgress())) {
                dcSupTaskInfos.get(i).setTaskProgressStr("已完成");
            } else {
                dcSupTaskInfos.get(i).setTaskProgressStr("未完成");
            }
        }
        return dcSupTaskInfo.getPage().setList(dcSupTaskInfos);
    }

    /**
     * 导出任务
     *
     * @param dcSupTaskAction
     * @param request
     * @param response
     */
    public void exportData(DcSupTaskInfoAction dcSupTaskAction, HttpServletRequest request, HttpServletResponse response) {
//		// 定义默认的导出文件名
//		String fileName = "反馈任务详情" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
//		// 设定时间格式
//		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//
//		// 关闭分页
//		dcSupTaskAction.setPage(null);
//		// 查询导出数据
//		List<DcSupTaskInfoAction> dcSupTaskInfoActions = getDcSupTaskInfoActions(dcSupTaskAction);
//
//		// 定义excel表头
//		List<String> headerList = new ArrayList<>(Arrays.asList("序号", "督办字号","任务内容", "牵头责任单位", "负责督办", "完成时限", "拟采取的工作举措", "存在问题", "最新进展情况", "是否完成"));
//		// 设置表头各列的宽度
//		List<Integer> headerWidthList = new ArrayList<>(Arrays.asList(1000,10000, 10000, -1, -1, -1, 10000, 10000, 10000, -1));
//
//		// 创建一个Sheet表，并导入数据
//		try (ExcelExport ee = new ExcelExport("反馈任务详情", headerList, headerWidthList)) {
//			// 添加行号
//			int index = 0;
//			// 遍历集合，获取导出数据
//			for (DcSupTaskInfoAction item : dcSupTaskInfoActions) {
//				index++;
//				// 创建空白行
//				Row row = ee.addRow();
//				// 序号
//				ee.addCell(row, 0, index);
//				// 督办字号
//				ee.addCell(row, 1, item.getDcSupTaskInfo().getMessageNumber());
//				// 任务事项
//				ee.addCell(row, 2, item.getDcSupTaskInfo().getTaskContent());
//				// 牵头责任单位
//				ee.addCell(row, 3, item.getLeaderOrgName());
//				// 负责督办
//				ee.addCell(row, 4, item.getDcSupTaskInfo().getTaskSupUserName() + "\n" + item.getDcSupTaskInfo().getTaskSupOrgName());
//
//				if (item.getFeedback() != null) {
//					// 完成时限
//					String tempStr = "";
//					if (item.getFeedback().getFeedbackEndTime() != null) {
//						tempStr = formatter.format(item.getFeedback().getFeedbackEndTime());
//					}
//					ee.addCell(row, 5, tempStr);
//					// 拟采取的工作举措
//					ee.addCell(row, 6, item.getFeedback().getFeedbackMeasure());
//					// 存在问题
//					ee.addCell(row, 7, item.getFeedback().getFeedbackAdvice());
//					// 最新进展情况
//					ee.addCell(row, 8, item.getFeedback().getFeedbackContent());
//					// 是否完成
//					ee.addCell(row, 9, DictUtils.getDictLabel("dc_feedback_progress", item.getFeedback().getFeedbackProgress(), null));
//				} else {
//					// 完成时限
//					ee.addCell(row, 5, "");
//					// 拟采取的工作举措
//					ee.addCell(row, 6, "");
//					// 存在问题
//					ee.addCell(row, 7, "");
//					// 最新进展情况
//					ee.addCell(row, 8, "");
//					// 是否完成
//					ee.addCell(row, 9, "");
//				}
//			}
//			ee.write(response, fileName);
//		}
    }

    /**
     * 导出任务 word
     *
     * @param dcSupTaskInfo
     * @param request
     * @param response
     */
    public void exportWord(DcSupTaskInfo dcSupTaskInfo, HttpServletRequest request, HttpServletResponse response) {
        // 定义默认的导出文件名
        String fileName = "反馈任务详情" + DateUtils.getDate("yyyyMMddHHmmss");

        // 关闭分页
        dcSupTaskInfo.setPage(null);
        // 查询导出数据
        List<DcSupTaskInfo> dcSupTaskInfoList = getDcSupTaskInfoActionsExport(dcSupTaskInfo);
        for (DcSupTaskInfo info:dcSupTaskInfoList) {
            System.out.println(info.getMessageNumber());
        }
        // 待导出数据
        RowRenderData header = Rows.of("序号", "任务内容", "牵头责任单位", "负责督办", "完成时限", "拟采取的工作举措", "存在问题", "最新进展情况", "是否完成").textFontFamily("黑体").textFontSize(12).center().create();
        Documents.DocumentBuilder documentBuilder = Documents.of();
        // 定义每列单元格宽度（一点点试出来的）
        double[] colWidths = new double[]{1.1, 3, 1.5, 1.5, 1.5, 7, 3, 8, 1.5};
        // 合并单元格
        MergeCellRule rule = MergeCellRule.builder().map(MergeCellRule.Grid.of(1, 0), MergeCellRule.Grid.of(1, 8)).build();
        for (int i = 0; i < dcSupTaskInfoList.size(); i++) {
            DcSupTaskInfo taskInfo = dcSupTaskInfoList.get(i);
            RowRenderData taskTitle = Rows.of(taskInfo.getTaskTitle(), null, null, null, null, null, null, null, null).textFontFamily("仿宋_GB2312").textFontSize(12).center().create();
            CellRenderData[] cells = new CellRenderData[9];
            for (int j = 0; j < cells.length; j++) {
                cells[j] = new CellRenderData();
            }
            // 序号（排序编号）
            cells[0].addParagraph(Paragraphs.of(taskInfo.getSortNum()).spacing(13, LineSpacingRule.EXACT).create());
            // 任务事项
            cells[1].addParagraph(Paragraphs.of(taskInfo.getTaskContent()).spacing(13, LineSpacingRule.EXACT).create());
            // 牵头责任单位
            String taskLeaderOrgName = taskInfo.getTaskLeaderOrgName();
            taskLeaderOrgName = taskLeaderOrgName.replace(",", "\n");
            cells[2].addParagraph(Paragraphs.of(taskLeaderOrgName).spacing(13, LineSpacingRule.EXACT).create());
            // 负责督办
            cells[3].addParagraph(Paragraphs.of(taskInfo.getTaskSupUserName() + "\n" + taskInfo.getTaskSupOrgName()).spacing(13, LineSpacingRule.EXACT).create());
            String tempStr = "";
            if (taskInfo.getTaskEndTime() != null) {
                tempStr = DateUtils.formatDate(taskInfo.getTaskEndTime(), "yyyy-MM-dd");
            }
            // 完成时限
            cells[4] = Cells.of(tempStr).create();
            if (taskInfo.getArrange() != null) {
                // 拟采取的工作举措
                cells[5].addParagraph(Paragraphs.of(taskInfo.getArrange().getArrangeContent3()).spacing(13, LineSpacingRule.EXACT).create());
                // 存在问题
                cells[6].addParagraph(Paragraphs.of(taskInfo.getArrange().getArrangeContent2()).spacing(13, LineSpacingRule.EXACT).create());
                // 最新进展情况
                cells[7].addParagraph(Paragraphs.of(taskInfo.getArrange().getArrangeContent()).spacing(13, LineSpacingRule.EXACT).create());
            } else {
                // 拟采取的工作举措
                cells[5].addParagraph(Paragraphs.of("").spacing(13, LineSpacingRule.EXACT).create());
                // 存在问题
                cells[6].addParagraph(Paragraphs.of("").spacing(13, LineSpacingRule.EXACT).create());
                // 最新进展情况
                cells[7].addParagraph(Paragraphs.of("").spacing(13, LineSpacingRule.EXACT).create());
            }
            // 是否完成
            cells[8].addParagraph(Paragraphs.of(DictUtils.getDictLabel("dc_task_arrange_status", taskInfo.getTaskProgress(), "未完成")).spacing(13, LineSpacingRule.EXACT).create());

            RowRenderData taskDetail = Rows.of(cells).textFontFamily("仿宋_GB2312").textFontSize(12).rowAtleastHeight(15).center().create();

            // 任务类型
            String taskTypeNameTemp = "";
            if (!"1".equals(taskInfo.getTaskProgress())) {
                taskTypeNameTemp += taskInfo.getTaskTypeName() + "（办理中）";
            } else {
                taskTypeNameTemp += taskInfo.getTaskTypeName() + "（已完成）";
            }
            documentBuilder.addParagraph(Paragraphs.of(Texts.of(taskTypeNameTemp).fontFamily("方正小标宋简体").fontSize(18).create()).center().create());
            // 表头，任务标题，任务详情
            documentBuilder.addTable(Tables.of(header, taskTitle, taskDetail).mergeRule(rule).width(0, colWidths).create());
            // 增加空段落用于做分页
            documentBuilder.addParagraph(Paragraphs.of().create());
        }

        DocumentRenderData documentRenderData = documentBuilder.create();
        XWPFTemplate template = XWPFTemplate.create(documentRenderData);

        // 每条隔一条任务，添加分页符
        List<XWPFParagraph> paragraphs = template.getXWPFDocument().getParagraphs();
        for (int i = 0; i < paragraphs.size(); i++) {
            if (StringUtils.isBlank(paragraphs.get(i).getText()) && i != paragraphs.size() - 1) {
                paragraphs.get(i).createRun().addBreak(BreakType.PAGE);
            }
        }

        // 获取表格元素，并设置页面格式为横向
        CTPPr ctpPr = template.getXWPFDocument().getDocument().getBody().addNewP().addNewPPr();
        CTSectPr ctSectPr = ctpPr.addNewSectPr();
        CTPageSz pageSize = ctSectPr.isSetPgSz() ? ctSectPr.getPgSz() : ctSectPr.addNewPgSz();
        pageSize.setOrient(STPageOrientation.LANDSCAPE);
        pageSize.setW(BigInteger.valueOf(842 * 20));
        pageSize.setH(BigInteger.valueOf(595 * 20));
        // 设置页边距1cm
        CTPageMar ctPageMar = ctSectPr.addNewPgMar();
        ctPageMar.setLeft(BigInteger.valueOf(567));
        ctPageMar.setTop(BigInteger.valueOf(567));
        ctPageMar.setRight(BigInteger.valueOf(567));
        ctPageMar.setBottom(BigInteger.valueOf(567));

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String tempFile = path + fileName + ".docx";
        try {
            template.writeToFile(tempFile);
        } catch (IOException e) {
            logger.error("导出word文件出错！", e);
            throw new ServiceException("导出word文件出错！");
        }
        FileUtils.downFile(new File(tempFile), request, response, fileName + ".docx");
        FileUtils.deleteFile(tempFile);
    }

    public void exportExcelData(DcSupTaskInfoAction dcSupTaskAction, HttpServletRequest request, HttpServletResponse response) throws Exception {
//		// 定义默认的导出文件名
//		String fileName = "反馈任务详情" + DateUtils.getDate("yyyyMMddHHmmss") + ".xls";
//		response.reset();
//		response.setContentType("application/octet-stream; charset=utf-8");
//		response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'"+ EncodeUtils.encodeUrl(fileName));
//		// 关闭分页
//		dcSupTaskAction.setPage(null);
//		// 查询导出数据
//		List<DcSupTaskInfoAction> dcSupTaskInfoActions = getDcSupTaskInfoActions(dcSupTaskAction);
//		List<DcSupTaskInfoExcel> list=new ArrayList<>();
//		for (DcSupTaskInfoAction dcSupTaskInfoAction:dcSupTaskInfoActions) {
//			DcSupTaskInfoExcel dcSupTaskInfoExcel=new DcSupTaskInfoExcel();
//			if(dcSupTaskInfoAction.getDcSupTaskInfo() !=null){
//				dcSupTaskInfoExcel.setTaskTitle(dcSupTaskInfoAction.getDcSupTaskInfo().getTaskTitle());
//				// 任务事项
//				dcSupTaskInfoExcel.setTaskContent(dcSupTaskInfoAction.getDcSupTaskInfo().getTaskContent());
//				// 负责督办
//				dcSupTaskInfoExcel.setTaskSupUserName(dcSupTaskInfoAction.getDcSupTaskInfo().getTaskSupUserName());
//			}
//			// 牵头责任单位
//			dcSupTaskInfoExcel.setLeaderOrgName(dcSupTaskInfoAction.getLeaderOrgName());
//
//			if(dcSupTaskInfoAction.getFeedback() !=null){
//				dcSupTaskInfoExcel.setFeedbackEndTime(dcSupTaskInfoAction.getFeedback().getFeedbackEndTime());
//				// 拟采取的工作举措
//				dcSupTaskInfoExcel.setFeedbackMeasure(dcSupTaskInfoAction.getFeedback().getFeedbackMeasure());
//				// 存在问题
//				dcSupTaskInfoExcel.setFeedbackAdvice(dcSupTaskInfoAction.getFeedback().getFeedbackAdvice());
//				// 最新进展情况
//				dcSupTaskInfoExcel.setFeedbackContent(dcSupTaskInfoAction.getFeedback().getFeedbackContent());
//				// 是否完成
//				dcSupTaskInfoExcel.setFeedbackProgress(DictUtils.getDictLabel("dc_feedback_progress", dcSupTaskInfoAction.getFeedback().getFeedbackProgress(), null));
//			}
//			list.add(dcSupTaskInfoExcel);
//		}
//		ExportParams deptExportParams = new ExportParams("反馈数据","");
//		// 设置sheet得名称
//		deptExportParams.setSheetName("反馈任务列表");
//
//		Map<String, Object> deptExportMap = new HashMap<>();
//		// title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
//		deptExportMap.put("title", deptExportParams);
//		// 模版导出对应得实体类型
//		deptExportMap.put("entity", DcSupTaskInfoExcel.class);
//		// sheet中要填充得数据
//		deptExportMap.put("data", list);
//
//		List<Map<String, Object>> sheetsList = new ArrayList<>();
//		sheetsList.add(deptExportMap);
//		Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
//		ServletOutputStream outputStream = response.getOutputStream();
//		workbook.write(outputStream);
//		outputStream.flush();
//		outputStream.close();
    }

    /**
     * 查询
     *
     * @param dcSupTaskInfo
     * @return
     */
    private List<DcSupTaskInfo> getDcSupTaskInfoActions(DcSupTaskInfo dcSupTaskInfo) {
        String userCode = UserUtils.getUser().getUserCode();
        String officeCode = sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode();
        // 数据范围
        if (!StringUtils.equals("system", userCode)) {
            // 本单位
            if ("0".equals(dcSupTaskInfo.getDataRange())||StringUtils.isBlank(dcSupTaskInfo.getDataRange())){
                dcSupTaskInfo.setCreateUnit(officeCode);
            }
            // 我创建的
            if ("1".equals(dcSupTaskInfo.getDataRange())){
                dcSupTaskInfo.setCreateBy(userCode);
            }
            // 本科室
            if ("2".equals(dcSupTaskInfo.getDataRange())){
                dcSupTaskInfo.setCreateOrg(EmpUtils.getOffice().getOfficeCode());
            }
        }

        //查询秘书科任务
        List<DcSupTaskInfo> dcSupTaskInfos = dcSupTaskActionDao.actionSecretaryFeedbackListQuery(dcSupTaskInfo);
        //获取taskId
        List<String> taskIds = dcSupTaskInfos.stream().map(DcSupTaskInfo::getId).collect(Collectors.toList());
        //拿taskId 查询任务整理集合
        List<DcSupTaskInfoArrange> arranges = dcSupTaskInfoArrangeDao.findListArranges(taskIds);
        //把数据转换成map集合
        Map<String, List<DcSupTaskInfoArrange>> arrangeMap = arranges.parallelStream().collect(Collectors.groupingBy(DcSupTaskInfoArrange::getTaskId));
        dcSupTaskInfos.forEach(item -> {
            item.setTaskLeaderOrgName(item.getTaskLeaderOrgName().replace(",", "\n"));
            List<DcSupTaskInfoArrange> back = arrangeMap.get(item.getId());
            if (back != null && !back.isEmpty()) {
                //整理内容
                DcSupTaskInfoArrange dcSupTaskInfoArrange = back.get(0);
                item.setArrange(dcSupTaskInfoArrange);
            }
        });

        return dcSupTaskInfos;
    }

    /**
     * 导出
     * @param dcSupTaskInfo
     * @return
     */
    private List<DcSupTaskInfo> getDcSupTaskInfoActionsExport(DcSupTaskInfo dcSupTaskInfo) {
        String userCode = UserUtils.getUser().getUserCode();
        String officeCode = sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode();
        // 数据范围
        if (!StringUtils.equals("system", userCode)) {
            // 本单位
            if ("0".equals(dcSupTaskInfo.getDataRange())||StringUtils.isBlank(dcSupTaskInfo.getDataRange())){
                dcSupTaskInfo.setCreateUnit(officeCode);
            }
            // 我创建的
            if ("1".equals(dcSupTaskInfo.getDataRange())){
                dcSupTaskInfo.setCreateBy(userCode);
            }
            // 本科室
            if ("2".equals(dcSupTaskInfo.getDataRange())){
                dcSupTaskInfo.setCreateOrg(EmpUtils.getOffice().getOfficeCode());
            }
        }

        //查询秘书科任务
        List<DcSupTaskInfo> dcSupTaskInfos = dcSupTaskActionDao.actionSecretaryFeedbackList(dcSupTaskInfo);
        //获取taskId
        List<String> taskIds = dcSupTaskInfos.stream().map(DcSupTaskInfo::getId).collect(Collectors.toList());
        //拿taskId 查询任务整理集合
        List<DcSupTaskInfoArrange> arranges = dcSupTaskInfoArrangeDao.findListArranges(taskIds);
        //把数据转换成map集合
        Map<String, List<DcSupTaskInfoArrange>> arrangeMap = arranges.parallelStream().collect(Collectors.groupingBy(DcSupTaskInfoArrange::getTaskId));
        dcSupTaskInfos.forEach(item -> {
            item.setTaskLeaderOrgName(item.getTaskLeaderOrgName().replace(",", "\n"));
            List<DcSupTaskInfoArrange> back = arrangeMap.get(item.getId());
            if (back != null && !back.isEmpty()) {
                //整理内容
                DcSupTaskInfoArrange dcSupTaskInfoArrange = back.get(0);
                item.setArrange(dcSupTaskInfoArrange);
            }
        });

        return dcSupTaskInfos;
    }

    public Page<ImageDto> getImageListData(ImageDto imageDto) {
        DcSupTaskInfo info = dao.getImageOne(imageDto.getId());

        DcSupTaskAction dcSupTaskAction = new DcSupTaskAction();
        dcSupTaskAction.setTaskId(imageDto.getId());
        dcSupTaskAction.setTaskStatus("2");
        List<DcSupTaskAction> listAction = this.getAction(dcSupTaskAction);
        DcSupTaskInfoArrange arrange = dao.getImageTwo(imageDto.getId());
        DcSupTaskAudit status = null;
        if(arrange!=null){
            status = dao.getImageThree(arrange.getId());
        }
        List<ImageDto> list = new ArrayList<>();
        ImageDto map = new ImageDto();
        map.setCreateDate(info.getCreateDate());
        map.setRemarks2("交办");
        map.setCreateBy(UserUtils.get(info.getCreateBy()).getUserName());
        map.setRemarks("");
        list.add(map);

        if(listAction!=null && listAction.size()>0){
            ImageDto map1 = new ImageDto();
            map1.setCreateDate(info.getCreateDate());
            map1.setRemarks2("签收");
            map1.setCreateBy(info.getTaskLeaderOrgName());
            map1.setRemarks("");
            list.add(map1);
        }

        if(arrange!=null) {
            ImageDto map2 = new ImageDto();
            map2.setCreateDate(arrange.getArrangeTime());
            map2.setRemarks2("反馈");
            map2.setCreateBy(arrange.getArrangeName());
            map2.setRemarks("");
            list.add(map2);
        }

        if(status!=null){
            ImageDto map3 = new ImageDto();
            map3.setCreateDate(status.getAuditTime());
            map3.setRemarks2("审核");
            map3.setCreateBy(status.getAuditorName());
            map3.setRemarks("");
            list.add(map3);
        }
        return imageDto.getPage().setList(list);
    }

    public Integer getFiveAndNightCount(String id) {
        return dao.getFiveAndNightCount(id);
    }

    public List<DcSupTaskAction> getListReceiveTime(DcSupTaskAction dcSupTaskAction) {
        return dao.getListReceiveTime(dcSupTaskAction);
    }

    public Page<DcSupTaskAction> listDataDelete(DcSupTaskAction dcSupTaskAction) {
        List<DcSupTaskAction> list = dao.listDataDelete(dcSupTaskAction);
        return dcSupTaskAction.getPage().setList(list);
    }
    public void deleteAction(DcSupTaskAction dcSupTaskAction) {
        List<DcSupTaskAction> actionList = dao.getActionListByActionid(dcSupTaskAction.getId());
//        DcSupTaskAction action = get(dcSupTaskAction.getId());
        //如果只有一条牵头责任单位,那就删除info表
        if (actionList.size()==1){
//            dao.deleteInfo(actionList.get(0).getTaskId());
            DcSupTaskInfo info = new DcSupTaskInfo();
            info.setId(actionList.get(0).getTaskId());
            dcSupTaskInfoService.deleteAll(info);
        }else{
            //如果不止一条,删掉info表的牵头责任单位编码和牵头责任单位名称
            DcSupTaskAction action = this.get(dcSupTaskAction.getId());
            DcSupTaskInfo info = dao.getInfoById(action.getTaskId());
            String orgCodeAction = action.getLeaderOrgCode();
            String orgNameAction = action.getLeaderOrgName();
            String orgCodeInfo = info.getTaskLeaderOrg();
            String orgNameInfo = info.getTaskLeaderOrgName();
            List<String> orgCodeInfoList = new ArrayList<>(Arrays.asList(orgCodeInfo.split(",")));
            orgCodeInfoList.removeIf(s->(s.equals(orgCodeAction)));
            String orgCodeInfoNew = String.join(",", orgCodeInfoList);

            List<String> orgNameInfoList = new ArrayList<>(Arrays.asList(orgNameInfo.split(",")));
            for (int i = 0; i < orgNameInfoList.size(); i++) {
                if(StringUtils.equals(orgNameInfoList.get(i),orgNameAction)){
                    orgNameInfoList.remove(i);
                    break;
                }
            }
            String orgNameInfoNew = String.join(",", orgNameInfoList);
            DcSupTaskInfo updateInfo = new DcSupTaskInfo();
            updateInfo.setId(info.getId());
            updateInfo.setTaskLeaderOrg(orgCodeInfoNew);
            updateInfo.setTaskLeaderOrgName(orgNameInfoNew);
            dao.updateInfo(updateInfo);

        }

        //获取反馈id用来找到审核记录
        String feedbackIds = dao.getFeedbackIdsByActionId(dcSupTaskAction.getId());
        //获取审核表id用来找到
        if(StringUtils.isNotBlank(feedbackIds)){
            String auditIds = dao.getAuditIdsByFeedbackIds(feedbackIds);
            if(StringUtils.isNotBlank(auditIds)){
                dao.deleteAuditTable(auditIds);
            }
        }
        dao.deleteAction(dcSupTaskAction);
    }

    public void updateTaskStatus(DcSupTaskAction action) {
        dao.updateTaskStatus(action);
    }

    public void updateDecomposeCreateBy(String decomposeTaskId, String transferOrgCode) {
        dao.updateDecomposeCreateBy(decomposeTaskId,transferOrgCode);
    }

    public List<Map> findLeaderOrg(String taskNo) {
        return dao.findLeaderOrg(taskNo);
    }

    public List<DcSupTaskAction> getAction(DcSupTaskAction dcSupTaskAction) {
        return dao.getAction(dcSupTaskAction);
    }

    public void scheduledInfoStatusEveryday() {
        //先查出info表task_status状态为2和7和8的数据
       List<DcSupTaskInfo> infoList = dao.getInfoNotFour();
        for (int i = 0; i < infoList.size(); i++) {
            //如果是闭环任务且状态为2,直接过滤
            if(StringUtils.equals(infoList.get(i).getNormalFlag(),"2")&&StringUtils.equals(infoList.get(i).getTaskStatus(),"2")){
                continue;
            }

            //如果是细化任务,refine表和action表数量不对应直接过滤
            if(StringUtils.equals(infoList.get(i).getNormalFlag(),"3")){
                //获取refine表的个数
                String refineNum = dao.getRefineNum(infoList.get(i).getId()).toString();
                //获取action表中的个数
                String actionNum = dao.getActionNum(infoList.get(i).getId()).toString();
                if(!StringUtils.equals(refineNum,actionNum)){
                    continue;
                }
            }

            //再查出action表中对应的task_id的数据
            List<DcSupTaskAction> actionList = dao.getActionNotFour(infoList.get(i).getId());
            //设置actionList的长度,当action全部为已结束时,设置info的状态为已结束
            Integer actionListFlag = actionList.size();
            for (int j = 0; j < actionList.size(); j++) {
                //再查询出反馈表中对应的actionId的数据
                String feedbackStatus = dao.getFeedbackStatus(actionList.get(j).getId());
                if(StringUtils.isNotBlank(feedbackStatus)){
                    //按逗号分割放到set中去重
                    HashSet<String> hashSet = new HashSet(Arrays.asList(feedbackStatus.split(",")));
                    //把set中的值放到list中循环
                    List<String> feedbackStatusList = new ArrayList<>(hashSet);
                    Integer feedbackListFlag = feedbackStatusList.size();
                    //无需反馈
                    if(feedbackStatus.contains("11")){
                        actionListFlag--;
                    }else{
                        for (int k = 0; k < feedbackStatusList.size(); k++) {
                            //判断feedbackStatus是否审核通过,是反馈通过标记减一
                            if(!feedbackStatusList.get(k).equals("5")&&!feedbackStatusList.get(k).equals("9")){
                                break;
                            }else{
                                feedbackListFlag--;
                            }
                        }
                    }
                        //结束反馈循环后标记为0,则全部反馈通过审核.分发标记减一,设置action状态为为已结束
                        if(feedbackListFlag==0||actionListFlag==0){
                            if(feedbackListFlag==0){
                                actionListFlag--;
                            }
                            //设置action状态为已结束
                            dao.setActionStatus(actionList.get(j));
                        }
                }
            }
            //如果actionList全部是已结束,设置info表的状态为已结束
            if(actionListFlag==0){
                //设置info表的状态为已结束
                dao.setInfoStatus(infoList.get(i));
            }
        }
    }

    public String changeActionTaskProgress() {
        try {
            //首先获取全部反馈表最新的feedback_status的数据
            List<DcSupTaskFeedback> actionList = dao.getActionList();

            for (DcSupTaskFeedback feedback:actionList) {
                DcSupTaskAction updateAction = new DcSupTaskAction();
                updateAction.setId(feedback.getActionId());
                updateAction.setRemarks2(DateUtils.getDateTime() + "定时任务");

                 //如果action的task_status为4,设置task_progress为4已完成
                if(StringUtils.equals(feedback.getTaskStatus(),"4")) {
                    updateAction.setTaskProgress("4");
                }else{
                    //未反馈
                    if(StringUtils.isBlank(feedback.getFeedbackProgress())){
                        updateAction.setTaskProgress("2");//逾期未反馈
                    }else{
                        //对应反馈表的feedback_progress
//                        updateAction.setTaskProgress(feedback.getFeedbackProgress());
                        if(feedback.getFeedbackProgress().equals("1")){//反馈的序时推进
                            updateAction.setTaskProgress("3");//任务的序时推进
                        }
                        if(feedback.getFeedbackProgress().equals("2")){//反馈的滞后时序
                            updateAction.setTaskProgress("1");//任务的进度滞后
                        }
                        if(feedback.getFeedbackProgress().equals("3")){//反馈的已完成
                            updateAction.setTaskProgress("4");//任务的已完成
                        }
                        if(feedback.getFeedbackProgress().equals("4")){//反馈的未完成
                            updateAction.setTaskProgress("5");//任务的未完成
                        }

                    }
                }

                dcSupTaskActionDao.updateProgress(updateAction);
            }
        }catch (Exception e){
            e.printStackTrace();
            return "失败";
        }
        return "成功";
    }

    public String scheduledActionTaskProgress() {
        try {
            //首先获取需要修改的action的id
            List<String> actionIdList = dao.getActionListNotFour();
            //批量修改action的progress为逾期未反馈
            dcSupTaskActionDao.updateProgress2(actionIdList,DateUtils.getDateTime() + "定时任务");
        }catch (Exception e){
            e.printStackTrace();
            return "失败";
        }
        return "成功";
    }

    public TaskReceiveDto getActionById(DcSupTaskAction action) {
        return dao.getActionById(action.getId());
    }
}